package com.example.musicplayer;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

// 在文件顶部添加
import androidx.core.content.ContextCompat;

public class SongAdapter extends ArrayAdapter<Song> {

    public SongAdapter(Context context, ArrayList<Song> songs) {
        super(context, 0, songs);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 获取当前歌曲
        Song song = getItem(position);

        // 检查是否有可复用的视图
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.song_item, parent, false);
        }

        // 找到视图组件
        TextView titleTextView = convertView.findViewById(R.id.song_title);
        TextView artistTextView = convertView.findViewById(R.id.song_artist);
        TextView durationTextView = convertView.findViewById(R.id.song_duration);

        // 设置数据
        titleTextView.setText(song.getTitle());
        artistTextView.setText(song.getArtist().equals("<unknown>") ? "未知艺术家" : song.getArtist());
        durationTextView.setText(formatTime(song.getDuration()));

        // 如果是当前播放的歌曲，设置特殊样式
        if (position == ((MusicPlayerActivity) getContext()).getCurrentSongIndex()) {
            // 使用 ContextCompat 获取颜色，提高兼容性
            titleTextView.setTextColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
        } else {
            titleTextView.setTextColor(ContextCompat.getColor(getContext(), android.R.color.black));
        }

        return convertView;
    }

    // 格式化时间
    private String formatTime(long milliseconds) {
        return String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes(milliseconds),
                TimeUnit.MILLISECONDS.toSeconds(milliseconds) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds))
        );
    }
}
